import React, { useState, useRef, useEffect } from 'react';

const DraggableChart = () => {
  const [data, setData] = useState([
    { id: 1, name: '产品A', value: 30, color: '#ff6b6b' },
    { id: 2, name: '产品B', value: 25, color: '#4ecdc4' },
    { id: 3, name: '产品C', value: 20, color: '#45b7d1' },
    { id: 4, name: '产品D', value: 15, color: '#96ceb4' },
    { id: 5, name: '产品E', value: 10, color: '#feca57' }
  ]);

  const [draggedItem, setDraggedItem] = useState(null);
  const [hoveredSegment, setHoveredSegment] = useState(null);
  const svgRef = useRef(null);

  const total = data.reduce((sum, item) => sum + item.value, 0);
  const centerX = 200;
  const centerY = 200;
  const radius = 120;

  // 计算饼图路径
  const calculatePieSlices = () => {
    let currentAngle = -Math.PI / 2; // 从顶部开始
    
    return data.map((item, index) => {
      const sliceAngle = (item.value / total) * 2 * Math.PI;
      const startAngle = currentAngle;
      const endAngle = currentAngle + sliceAngle;
      
      const x1 = centerX + radius * Math.cos(startAngle);
      const y1 = centerY + radius * Math.sin(startAngle);
      const x2 = centerX + radius * Math.cos(endAngle);
      const y2 = centerY + radius * Math.sin(endAngle);
      
      const largeArcFlag = sliceAngle > Math.PI ? 1 : 0;
      
      const pathData = [
        `M ${centerX} ${centerY}`,
        `L ${x1} ${y1}`,
        `A ${radius} ${radius} 0 ${largeArcFlag} 1 ${x2} ${y2}`,
        'Z'
      ].join(' ');
      
      // 计算标签位置
      const labelAngle = startAngle + sliceAngle / 2;
      const labelRadius = radius * 0.7;
      const labelX = centerX + labelRadius * Math.cos(labelAngle);
      const labelY = centerY + labelRadius * Math.sin(labelAngle);
      
      currentAngle = endAngle;
      
      return {
        ...item,
        pathData,
        labelX,
        labelY,
        percentage: ((item.value / total) * 100).toFixed(1)
      };
    });
  };

  const pieSlices = calculatePieSlices();

  // 拖拽处理
  const handleDragStart = (e, item) => {
    setDraggedItem(item);
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', e.target.outerHTML);
  };

  const handleDragOver = (e) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  };

  const handleDrop = (e, targetItem) => {
    e.preventDefault();
    
    if (!draggedItem || draggedItem.id === targetItem.id) return;
    
    const newData = [...data];
    const draggedIndex = newData.findIndex(item => item.id === draggedItem.id);
    const targetIndex = newData.findIndex(item => item.id === targetItem.id);
    
    // 交换位置
    [newData[draggedIndex], newData[targetIndex]] = [newData[targetIndex], newData[draggedIndex]];
    
    setData(newData);
    setDraggedItem(null);
  };

  const handleDragEnd = () => {
    setDraggedItem(null);
  };

  // 编辑数值
  const handleValueChange = (id, newValue) => {
    const value = Math.max(0, Math.min(100, parseInt(newValue) || 0));
    setData(data.map(item => 
      item.id === id ? { ...item, value } : item
    ));
  };

  // 添加新项目
  const addNewItem = () => {
    const newId = Math.max(...data.map(item => item.id)) + 1;
    const colors = ['#e74c3c', '#9b59b6', '#3498db', '#1abc9c', '#f39c12', '#34495e'];
    const newColor = colors[data.length % colors.length];
    
    setData([...data, {
      id: newId,
      name: `产品${String.fromCharCode(65 + data.length)}`,
      value: 5,
      color: newColor
    }]);
  };

  // 删除项目
  const removeItem = (id) => {
    if (data.length > 1) {
      setData(data.filter(item => item.id !== id));
    }
  };

  return (
    <div className="draggable-chart">
      <div className="chart-content">
        {/* 饼图 */}
        <div className="pie-chart-container">
          <svg
            ref={svgRef}
            width="400"
            height="400"
            viewBox="0 0 400 400"
            className="pie-chart"
          >
            {pieSlices.map((slice) => (
              <g key={slice.id}>
                <path
                  d={slice.pathData}
                  fill={slice.color}
                  stroke="#fff"
                  strokeWidth="2"
                  className={`pie-slice ${hoveredSegment === slice.id ? 'hovered' : ''}`}
                  onMouseEnter={() => setHoveredSegment(slice.id)}
                  onMouseLeave={() => setHoveredSegment(null)}
                />
                <text
                  x={slice.labelX}
                  y={slice.labelY}
                  textAnchor="middle"
                  dominantBaseline="middle"
                  className="pie-label"
                  fill="white"
                  fontSize="12"
                  fontWeight="bold"
                >
                  {slice.percentage}%
                </text>
              </g>
            ))}
            
            {/* 中心圆 */}
            <circle
              cx={centerX}
              cy={centerY}
              r="40"
              fill="rgba(255, 255, 255, 0.9)"
              stroke="#ddd"
              strokeWidth="2"
            />
            <text
              x={centerX}
              y={centerY - 5}
              textAnchor="middle"
              className="center-text"
              fill="#333"
              fontSize="14"
              fontWeight="bold"
            >
              总计
            </text>
            <text
              x={centerX}
              y={centerY + 15}
              textAnchor="middle"
              className="center-value"
              fill="#666"
              fontSize="16"
              fontWeight="bold"
            >
              {total}
            </text>
          </svg>
        </div>

        {/* 数据列表 */}
        <div className="data-list">
          <h3>数据项目</h3>
          <div className="data-items">
            {data.map((item) => (
              <div
                key={item.id}
                className={`data-item ${draggedItem?.id === item.id ? 'dragging' : ''}`}
                draggable
                onDragStart={(e) => handleDragStart(e, item)}
                onDragOver={handleDragOver}
                onDrop={(e) => handleDrop(e, item)}
                onDragEnd={handleDragEnd}
              >
                <div className="item-info">
                  <div
                    className="color-indicator"
                    style={{ backgroundColor: item.color }}
                  ></div>
                  <input
                    type="text"
                    value={item.name}
                    onChange={(e) => setData(data.map(d => 
                      d.id === item.id ? { ...d, name: e.target.value } : d
                    ))}
                    className="item-name"
                  />
                </div>
                
                <div className="item-controls">
                  <input
                    type="number"
                    value={item.value}
                    onChange={(e) => handleValueChange(item.id, e.target.value)}
                    className="item-value"
                    min="0"
                    max="100"
                  />
                  <button
                    onClick={() => removeItem(item.id)}
                    className="remove-btn"
                    disabled={data.length <= 1}
                  >
                    ×
                  </button>
                </div>
                
                <div className="drag-handle">⋮⋮</div>
              </div>
            ))}
          </div>
          
          <button onClick={addNewItem} className="add-item-btn">
            + 添加项目
          </button>
        </div>
      </div>

      {/* 图例 */}
      <div className="chart-legend">
        <h4>图例</h4>
        <div className="legend-items">
          {data.map((item) => (
            <div key={item.id} className="legend-item">
              <div
                className="legend-color"
                style={{ backgroundColor: item.color }}
              ></div>
              <span className="legend-name">{item.name}</span>
              <span className="legend-value">
                {item.value} ({((item.value / total) * 100).toFixed(1)}%)
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default DraggableChart;